package avicit.bdp.dcs.utils.api.header;

import avicit.bdp.dcs.utils.api.Configuration;
import avicit.bdp.dcs.utils.api.enums.AuthType;
import avicit.bdp.dcs.utils.api.enums.Key;
import avicit.platform6.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;

import java.util.Base64;

public abstract class HeaderAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(HeaderAdapter.class);

    /**
     * 构建Header请求头信息
     * @param readerSliceConfig
     * @return
     */
    public abstract Object buildHttpEntity(Configuration readerSliceConfig);

    /**
     * 追加权限认证参数
     * @param readerSliceConfig
     * @param headers
     */
    public void appendAuthParam(Configuration readerSliceConfig, HttpHeaders headers){
        String authTypeStr = readerSliceConfig.getString(Key.AUTH_TYPE);
        Configuration authParam = readerSliceConfig.getConfiguration(Key.AUTH_PARAM);
        AuthType authType = AuthType.getAuthType(authTypeStr);
        switch (authType) {
            case NO_AUTH:
                break;
            case BASIC_AUTH:
                String username = authParam.getString(Key.USERNAME);
                String password = authParam.getString(Key.PASSWORD);
                headers.add(Key.AUTHORIZATION, Key.BASIC + Key.SPACE +
                        Base64.getUrlEncoder().encodeToString((username + Key.COLON + password).getBytes()));
                break;
            case TOKEN_AUTH:
                String token = authParam.getString(Key.TOKEN);
                headers.add(Key.X_ACCESS_TOKEN, token);
                break;
            case API_KEY:
                String key = authParam.getString(Key.KEY);
                String value = authParam.getString(Key.VALUE);
                headers.add(key, value);
                break;
            default:
                String msg = String.format("不支持的认证类型%s", authType);
                LOG.error(msg);
                throw new BusinessException(msg);
        }
    }

}
